package com.qhx.rtkcloud.tcp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RtcmMeshCoder {
    private static final  long SPACE = 100;
    private static final  long RADIUS = 10000;


    private static  List<long[]> getMeshLocations(long x, long y) {

        long minX = x - RADIUS;
        long minY = y - RADIUS;
        long maxX = x + RADIUS;
        long maxY = y + RADIUS;
        List<long[]> locations = new ArrayList<>();

        while(minX <= maxX) {
          Long baseY = minY;
          while(baseY <= maxY) {
              locations.add(new long[]{minX, baseY});
              baseY += SPACE;
          }
            minX += SPACE;
        }
        return locations;

    }

    private static byte[] composeMesh(byte[] referNode,long x, long y, long z) {

       List<long[]> meshLocations = getMeshLocations(x, y);
       List<Byte> bytes = new ArrayList<>();
       for (int i = 0; i < meshLocations.size(); i++) {
          byte[] points = getMeshPoint(referNode, i, meshLocations.get(i)[0],meshLocations.get(i)[1], z);
          for (byte b : points) {
               bytes.add(b);
           }
       }

        bytes.add((byte)0xEE);
        bytes.add((byte)0xDF);

       byte[] result = new byte[bytes.size()];
       for (int i = 0; i < bytes.size(); i++) {
           result[i] = bytes.get(i).byteValue();
       }
       return result;


    }






    private static byte[] getMeshPoint(byte[] rtcm, int num, long x, long y, long z) {
        int length = 19 + rtcm.length + 3;
        byte[] result = new byte[length];
        result[0] = (byte) 0xDD;
        result[1] =  (byte)((length - 3) >> 8);
        result[2] =  (byte)((length - 3) & 255);
        result[3] = (byte) (num >> 6);
        result[4] = (byte) ((num & 63)<<2 + (x >>36));
        result[5] = (byte) ((x >> 28) & 255);
        result[6] = (byte) ((x >> 20) & 255);
        result[7] = (byte) ((x >> 12) & 255);
        result[8] = (byte) ((x>>4) & 255);
        result[9] = (byte) (((x & 15) << 4) + (y >>34));
        result[10] = (byte) ((y>>26) & 255);
        result[11] = (byte) ((y>>18) & 255);
        result[12] = (byte) ((y>>10) & 255);
        result[13] = (byte) ((y>>2) & 255);
        result[14] = (byte) (((y&3)<< 6) + (z >> 32));
        result[15] = (byte) ((z>>24) & 255);
        result[16] = (byte) ((z>>16) & 255);
        result[17] = (byte) ((z>>8) & 255);
        result[18] = (byte) ((z) & 255);
        for (int i = 0; i < rtcm.length; i++) {
            result[i + 19] = rtcm[i];
        }
        result[length -3 ] =1;
        result[length -2 ] =2;
        result[length -1 ] =3;
        return result;


    }
}
